package com.example.mycontinuation

import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"
    lateinit var button: Button
    lateinit var button2: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById(R.id.button)
        button2 = findViewById(R.id.button2)
        button.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                val request1 = request1(10)
                val request2 = request2(request1)
                val request3 = request3(request2)
                button.updateUI(request3)
            }
        }
        button2.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                val request1 = request1(20)
                val deferred1 = async { request2(request1) }
                val deferred2 = async { request3(request1) }
                button2.updateUI("${deferred1.await()} | ${deferred2.await()} ")
            }
        }
    }

    private suspend fun request1(int: Int): Int {
        val i = int * int
        delay(1000)
        log("request1:$i")
        return i
    }

    private suspend fun request2(int: Int): Int {
        val i = int * int
        delay(2000)
        log("request2:$i")
        return i
    }

    private suspend fun request3(int: Int): Int {
        delay(2000)
        var num = int * int
        var reversed = 0
        while (num != 0) {
            val digit = num % 10
            reversed = reversed * 10 + digit
            num /= 10
        }
        log("request3:$num")
        return num
    }

    private suspend fun Button.updateUI(any: Any) {
        withContext(Dispatchers.Main) {
            this@updateUI.text = any.toString()
        }
    }


}